"""
    TorrentBrowser plugin for XBMC
    Copyright (C) 2011-2012 Markus Langenoja
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
    Function [TBXbmc]
    -----------------
    * listCategories() - Lists categories found in TBSites
    * buildList(params) - Builds and shows list in XBMC
"""
import xbmcgui, xbmcplugin
import threading, urllib, sys
import TBTools

class TBXbmc(TBTools.TBTools):
    __info__ = sys.modules[ "__main__" ].__info__
    __deb__ = sys.modules[ "__main__" ].__deb__
    __plugin__ = sys.modules[ "__main__" ].__plugin__
        
    __browser__ = sys.modules[ "__main__" ].__browser__
    __scraper__ = sys.modules[ "__main__" ].__scraper__
    __categories__ = sys.modules[ "__main__" ].__categories__
        
    def listCategories(self):
        __totalitems__ = len(self.__categories__)
        i = 1
        for cat in self.__categories__:
            get = cat.get
            listItem = xbmcgui.ListItem(get('title'),iconImage = 'DefaultFolder.png')
            listItem.setInfo('video', {'title':get('title'),'size':i})
            i += 1
            if get('catlabel') == 'SEARCH':
                action = 'search'
            else:
                action = 'get_movies'
            url = sys.argv[0] + '?action=%s&page=1&category=%s' % (action,get('catlabel'))
            xbmcplugin.addDirectoryItem(int(sys.argv[1]), url, listItem, isFolder=True, totalItems =__totalitems__)
            
        xbmcplugin.addSortMethod(int(sys.argv[1]),xbmcplugin.SORT_METHOD_SIZE)
        return xbmcplugin.endOfDirectory(int(sys.argv[1]))
    
    def buildList(self, params={}):
        get = params.get
        ''' DEBUG PRINT PARAMS '''
        if (not get('page')) and (not get('id')) and (not get('searchstring')): 
            print 'ERROR: Either Page, ID nor Searchstring supplied.'
        
        # Get list of items needed to be parsed
        items = self.__browser__.getItems(params)

        try:
            totalItems = len(items)+1
        except:
            print 'SOMETHING WENT WRONG, NO ITEMS PARSED'
            return
        # Title, Icon, Thumbnail
        # Scraped Information
        for i in items:
            item = items[i]
            item['totalitems'] = totalItems
            # This next is for sorting purposes
            item['size'] = i
            # This is for the listing
            item['page'] = get('page')
            # Needed info for XBMC: Title, Icon, Thumbnail (get from scrape)
            if item.get('folder'):
                item['icon'] = 'DefaultFolder.png'
            else:
                item['icon'] = 'DefaultVideo.png'
                
            thread = Thread(item)
            thread.start()
        
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
                thread.join()
        
        ''' Add next page and finnish list '''
        if get('action') == 'get_movies':
            listItem = xbmcgui.ListItem('Next Page',iconImage='DefaultFolder.png',thumbnailImage='')
            listItem.setInfo('video', infoLabels={'title':'NEXT PAGE','size':int(len(items)+1)})
            url = sys.argv[0] + '?action=get_movies&category=%s&page=%s' % (get('category'),int(get('page'))+1)
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=listItem,isFolder=True,totalItems = totalItems)

        xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE)
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
                                  
    def buildItem(self,item):
        get = item.get
        # Get what to scrape from settings
        __info2xbmc__ = self.sumInfo2Xbmc()
     
        # Extract information needed for the list building
        __totalitems__ = get('totalitems')
        __folder__ = get('folder')
        
        ''' BUILD URL '''       
        url = sys.argv[0]
        if __folder__:
            action = 'get_formats'
            addon = '&page=%s&id=%s' % (int(get('page')),get('id'))
        else:
            action = 'download'
            addon = '&dlurl=%s&filename=%s' % (urllib.quote_plus(get('downloadurl')),urllib.quote_plus(get('filename')))
            
        url = url + '?action=%s%s' % (action,addon)
            
        #Scrape information if not requesting via ID
        if get('scrape'):
            item = self.__scraper__.scrapeInfo(item)

        ''' Building listitem '''
        # If poster is checked in settings, use poster as thumbnail (will fail for ID request)
        if __info2xbmc__['poster']:
            try:
                thumbnail = get('poster')
            except: thumbnail = ''
        else:
            thumbnail = ''
                        
        # Initiate listItem
        title = self.replaceBadSigns(get('title'))
        listItem = xbmcgui.ListItem(title,iconImage=get('icon'),thumbnailImage=thumbnail)
        
        # Build listItem with information obtained from TheMovieDB scrape      
        for label in __info2xbmc__.keys():
            try:
                if get(label):
                    if __info2xbmc__[label] and (label != 'poster') and (label != 'backdrop') and (label != 'title'):
                        data = get(label)
                        listItem.setInfo(type='video', infoLabels={label:data})
                    elif (label == 'title'):
                        listItem.setInfo(type='video', infoLabels={label:title})
                    elif (label == 'backdrop'):
                        try:
                            listItem.setProperty('Fanart_Image',get('backdrop'))
                        except: pass
                    try: 
                        listItem.setInfo(type='video', infoLabels={'studio':urllib.quote_plus(get('filename'))})
                    except: pass
            except: pass
                
        return xbmcplugin.addDirectoryItem(int(sys.argv[1]), url, listItem, isFolder=__folder__, totalItems =__totalitems__)

class Thread(threading.Thread):
    def __init__(self,item):
        self.item = item
        threading.Thread.__init__(self)
        
    def run(self):
        t = TBXbmc()
        t.buildItem(self.item)